package com.wyc.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 *  http请求类
 * */
@Service
public class HttpClient {

    @Autowired
    MD5 md5;

    //Get
    public String getclient(String url,Map map) throws UnsupportedEncodingException {
        Map mapmd5 = md5.getSign(map);
        String params = "sign="+ URLEncoder.encode((String) mapmd5.get("sign"), "utf-8")+"&timestamp="+URLEncoder.encode((String)mapmd5.get("timestamp"), "utf-8");
        RestTemplate client = new RestTemplate();
        System.out.println(url+params);
        return client.getForObject(url+params, String.class);
    }

    //post
    public String postclient(String url, String params,Map map) {
        RestTemplate restTemplate=new RestTemplate();
        Map mapmd5 = md5.getSign(map);
        params += "&sign="+mapmd5.get("sign")+"&timestamp="+mapmd5.get("timestamp");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        String body = "gid="+ URLEncoder.encode("11", "utf-8")+"&sign="+URLEncoder.encode("8b71dac96191c7329320e95c61b450bb", "utf-8")+"&timestamp="+URLEncoder.encode("20180326204554", "utf-8");
        HttpEntity entity = new HttpEntity(params, headers);
        System.out.println(entity);
        System.out.println(url);
        return restTemplate.exchange(url, HttpMethod.POST, entity, String.class).getBody();
    }
}
